package com.dikang.yygh.oss.controller;

import com.dikang.yygh.common.exception.YyghException;
import com.dikang.yygh.common.result.Result;
import com.dikang.yygh.common.result.ResultCodeEnum;
import com.dikang.yygh.oss.service.FileService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Api("文件上传接口")
@RestController
@RequestMapping("/api/oss/file")
public class FileApiController {
    @Autowired
    private FileService fileService;
    // 上传文件到阿里云oss
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file){
        // 代码中的file对象，为 MultipartFile file
        List<String> imgsType = new ArrayList<>(Arrays.asList("image/jpg", "image/jpeg", "image/png"));
        if (!imgsType.contains(file.getContentType().toLowerCase())) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        if (file.getSize() <= 0L) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

/**
 * 限制在1M以内
 */
        if (file.getSize() > (1024 * 1024)) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        // 获取上传文件
        String url =fileService.upload(file);
        return Result.ok(url);
    }
}
